package com.xckj.cycling.activity

import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.widget.ImageView
import androidx.core.content.FileProvider
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.FitCenter
import com.junca.android.base.CViewBinding
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.photoview.OnPhotoTapListener
import com.xckj.cycling.R
import com.xckj.cycling.context.AppContext
import com.xckj.cycling.databinding.ActivityEditHeadBinding
import com.xckj.cycling.dialog.EditHeadDialog
import com.xckj.cycling.event.EventUploadAvatar
import com.xckj.cycling.framework.BaseActivityKt
import com.xckj.cycling.utils.FileUtils
import com.xckj.cycling.utils.GlideEngine
import com.yalantis.ucrop.UCrop
import com.yalantis.ucrop.UCropActivity
import org.greenrobot.eventbus.EventBus
import java.io.File

/**
 * 编辑头像
 */
class EditHeadActivity : BaseActivityKt() {
    @CViewBinding
    lateinit var viewBinding: ActivityEditHeadBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        loginViewModel.userCenterLiveData.observe(this) {
            Glide.with(this).load(it.userinfo?.avatar).transform(FitCenter())
                .into(viewBinding.photo)
        }
        viewBinding.photo.setOnPhotoTapListener(object : OnPhotoTapListener {
            override fun onPhotoTap(view: ImageView?, x: Float, y: Float) {
                showBottomDialog()
            }

        })
        viewBinding.title.tvTitle.text = getString(R.string.title_avatar)
    }

    private fun showBottomDialog() {
        EditHeadDialog(this).show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                UCrop.REQUEST_CROP -> {
                    var file = getOuputFile()
                    if (file != null && file.exists() && file.name.endsWith(".jpg")) {
                        Glide.with(this).load(file).skipMemoryCache(true) // 不使用内存缓存
                            .diskCacheStrategy(DiskCacheStrategy.NONE) // 不使用磁盘缓存
                            .into(viewBinding.photo)
                        uploadImage(file.path)
                    }
                }
            }
        }
    }

    private fun uploadImage(path: String) {
        showLoading()
        loginViewModel.uploadAvatar(path) {
            hideDialog()
            EventBus.getDefault().post(EventUploadAvatar)
            if (!it.isSuccessful) {
                showMessage(it.msg)
            }
        }
    }

    fun camera() {
        PictureSelector.create(this)
            .openCamera(SelectMimeType.ofImage())
            .setLanguage(LanguageConfig.ENGLISH)
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {
                    result?.get(0)?.realPath?.let { it1 -> startCrop(it1) }

                }

                override fun onCancel() {

                }
            })
    }

    fun gallery() {
        PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setLanguage(LanguageConfig.ENGLISH)
            .setSelectionMode(SelectModeConfig.SINGLE)
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                    result?.get(0)?.realPath?.let { it1 -> startCrop(it1) }
                }

                override fun onCancel() {

                }

            })
    }

    private fun startCrop(path: String) {
        val uri: Uri = if (Build.VERSION.SDK_INT >= 24) {
            val applicationId: String = packageName
            FileProvider.getUriForFile(
                this,
                "$applicationId.FileProvider",
                File(path)
            )
        } else {
            Uri.fromFile(File(path))
        }

        //初始化，第一个参数：需要裁剪的图片；第二个参数：裁剪后图片
        val uCrop = UCrop.of<Any>(
            uri,
            Uri.fromFile(
                getOuputFile()
            )
        )
        //初始化UCrop配置
        val options = UCrop.Options()
        options.setHideBottomControls(true)
        options.setShowCropGrid(false)
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.NONE, UCropActivity.NONE)
        options.withAspectRatio(1f, 1f)
        options.setCompressionQuality(90)
        options.setStatusBarColor(Color.parseColor("#000000")) //设置状态栏颜色
        options.setToolbarColor(Color.parseColor("#000000"))
        options.setToolbarWidgetColor(Color.parseColor("#ffffff"))
        uCrop.withOptions(options)
        //跳转裁剪页面
        uCrop.start(this)
    }

    /**
     * 裁剪头像输出目录
     */
    private fun getOuputFile(): File {
        return File(
            FileUtils.createFolder(AppContext.globalContext().cacheDir.path + "/userPhoto/").path,
            "crop.jpg"
        )
    }
}